<template>
  <div class="container" v-if="!loading">
    <div class="header">
      <div class="city">{{ gcity }}</div>
      <star-search v-model="businessName" @search="onSearch" @clear="onClear">
        <template #action>
          <span @click="onClickButton">搜索</span>
        </template>
      </star-search>
    </div>
    <van-pull-refresh v-model="pullLoading" @refresh="onRefresh">
      <div class="home-container">
        <van-swipe :autoplay="3000" lazy-render>
          <van-swipe-item v-for="image in imageList" :key="image">
            <img :src="image" />
          </van-swipe-item>
        </van-swipe>
        <div class="business">
          <div class="title">商家列表</div>
          <Business :business-list="businessList" :total="total" @getBusinessList="getBusinessList" />
        </div>
      </div>
    </van-pull-refresh>
  </div>
  <star-loading v-else />
</template>
<script setup lang="ts">
const Business = defineAsyncComponent(() => import('./components/Business.vue'))
import { getBusinessPageAPI } from '@/api/business'
import type { BusinessItemResult } from '@/types/business'
import { showFailToast } from 'vant'
import { ref, onMounted, defineAsyncComponent } from 'vue'
import useMap from '@/hooks/useMap'
import { useloadingStore } from '@/stores/modules/loading'

const imageImporters = [
  () => import('/images/lb_1.webp'),
  () => import('/images/lb_2.webp'),
  () => import('/images/lb_3.webp'),
];

const imageList = ref<string[]>([]);

// 图片懒加载函数
const lazyLoadImages = async () => {
  try {
    // 先加载第一张图片
    const firstModule = await imageImporters[0]();
    imageList.value.push(firstModule.default);

    // 延迟加载剩余图片
    setTimeout(async () => {
      const remainingImporters = imageImporters.slice(1);
      const modules = await Promise.all(remainingImporters.map(importer => importer()));
      imageList.value.push(...modules.map(module => module.default));
    }, 500);
  } catch (err) {
    console.error('图片加载失败:', err);
  }
};

const gcity = ref('定位中')
// 城市定位
const { loadMap, handleAddress } = useMap()
// 下拉刷新
const pullLoading = ref(false)

const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const businessName = ref('')
// 商家列表
const businessList = ref<BusinessItemResult[]>([])
const loadingStore = useloadingStore()
const loading = loadingStore.loading
// 重置数据
const resetBusinessList = () => {
  businessList.value = []
  page.value = 1
  total.value = 0
}
// 下拉刷新
const onRefresh = async () => {
  loadingStore.showLoading()
  pullLoading.value = true
  resetBusinessList()
  try {
    await getBusinessList()
    loadingStore.hideLoading()
    pullLoading.value = false
  } catch (e) {
    console.log(e)
    showFailToast('网络异常,请重试')
  }
}

// 获取商家列表
const getBusinessList = async () => {
  const params = {
    page: page.value,
    pageSize: pageSize.value,
  }
  try {
    const { data } = await getBusinessPageAPI(params)
    if (businessList.value.length === 0) {
      businessList.value = data.records
    } else {
      businessList.value = [...businessList.value, ...data.records]
    }
    total.value = data.total
    page.value += 1
    if (businessList.value.length >= total.value) {
      // 如果已加载的数据量等于总数据量，则设置加载完成
      return
    }
  } catch (error) {
    console.log(error)
    showFailToast('获取数据失败')
  }
}
const onSearch = (val: string) => {
  businessName.value = val
}
// 搜索
const onClickButton = async () => {
  console.log(businessName.value)
  const params = {
    page: (page.value = 1),
    pageSize: pageSize.value,
    name: businessName.value,
  }
  try {
    const { data } = await getBusinessPageAPI(params)
    businessList.value = data.records
  } catch (error) {
    console.log(error)
  }
}
// 搜索清除
const onClear = async () => {
  page.value = 1
  pageSize.value = 10
  total.value = 0
  businessName.value = ''
  businessList.value = []
  await getBusinessList()
}

// 获取定位城市
const getAddress = async (lat: number, lng: number) => {
  try {
    await loadMap()
    const result = await handleAddress(lat, lng)
    gcity.value = result.regeocode.addressComponent.city
    const cityName = result.regeocode.addressComponent.city + result.regeocode.addressComponent.district
    localStorage.setItem('city', cityName)
  } catch (e) {
    console.log(e)
  }
}

const error = ref<GeolocationPositionError | null>(null)
// 获取定位
const getLocation = () => {
  const geolocation = localStorage.getItem('geolocation')
  if (geolocation) {
    try {
      const { city } = JSON.parse(geolocation)
      gcity.value = city
    } catch (e: any) {
      localStorage.removeItem('geolocation')
      console.error('解析本地存储的地理位置信息时出错：', e.message)
    }
  } else {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (pos) => {
          console.log(pos)
          getAddress(pos.coords.latitude, pos.coords.longitude)
        },
        (err) => {
          console.log(err)
          error.value = err
        },
        {
          enableHighAccuracy: true,
          timeout: 5000,
          maximumAge: 0,
        },
      )
    } else {
      showFailToast('当前未开启地理定位')
    }
  }
}

onMounted(async () => {
  loadingStore.showLoading()
  lazyLoadImages()
  getLocation()
  await getBusinessList()
  loadingStore.hideLoading()
})
</script>
<style scoped lang="scss">
.header {
  height: 46px;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 1;
  display: flex;
  background: var(--box-background);

  .city {
    width: 60px;
    margin: 0 10px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.home-container {
  margin-top: 46px;
  height: calc(100vh - 46px);
  display: flex;
  flex-direction: column;
  overflow: auto;
}



img {
  object-fit: cover;
  background-size: contain;
}

.business {
  flex: 1;

  .title {
    margin: 10px;
  }
}
</style>
